//
//  SelectViewController.m
//  liwushuo
//
//  Created by qf1 on 16/4/15.
//  Copyright (c) 2016年 ZJH. All rights reserved.
//

#import "SelectViewController.h"
#import "HotDetailViewController.h"

@interface SelectViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout>

@property (retain,nonatomic)NSMutableString * url;
@property (retain,nonatomic)NSMutableDictionary * contentDict;

@end

@implementation SelectViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    MBProgressHUD * hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.labelText = @"正在加载";
    hud.detailsLabelText = @"请稍后";
    [hud show:YES];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"back"] style:UIBarButtonItemStylePlain target:self action:@selector(backAction)];

//    初始化改变选择页面的参数
    _contentDict = [[NSMutableDictionary alloc] initWithObjects:@[@"",@"",@"20",@"0",@"",@""] forKeys:@[@"price",@"personality",@"limit",@"offset",@"target",@"scene"]];
//    初始化选择页面接口
    _url = [[NSMutableString alloc] init];
    self.title = @"挑选礼物";
    self.navigationController.navigationBar.titleTextAttributes = @{NSFontAttributeName:[UIFont boldSystemFontOfSize:21],NSForegroundColorAttributeName:[UIColor whiteColor]};
    _dataArray = [[NSMutableArray alloc] init];
    [self createView];
    [self getData];
}

- (void)backAction{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)createView{
    UICollectionViewFlowLayout * layout = [[UICollectionViewFlowLayout alloc] init];
    [layout setScrollDirection:UICollectionViewScrollDirectionVertical];
    
    
    _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 40, theScreenWidth, theScreenHeight - 40 - 64) collectionViewLayout:layout];
    _collectionView.backgroundColor = [UIColor colorWithRed:245 / 255.0 green:245 / 255.0 blue:245 / 255.0 alpha:1];
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    [_collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"cell"];
    [self.view addSubview:_collectionView];
}

- (void)getData{
    __weak SelectViewController * weakself = self;
    NetWorkManager * manager = [[NetWorkManager alloc] init];
    [manager getSelectContentDataWithUrl:@"http://api.liwushuo.com/v2/search/item_by_type?limit=20&offset=0" andBlock:^(id respond) {
        _dataArray = [[NSMutableArray alloc] initWithArray:respond];
        [_collectionView reloadData];
    }];
    [manager getSelectDataWithUrl:@"http://api.liwushuo.com/v2/search/item_filter" andBlock:^(id respond) {
        _naviDataArray = [[NSMutableArray alloc] initWithArray:respond];
        UIView * view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, theScreenWidth, 40)];
        view.backgroundColor = [UIColor whiteColor];
        [self.view addSubview:view];
        for (int i = 0; i < 4; i ++) {
            [view addSubview:({
                UIButton * btn = [UIButton buttonWithType:UIButtonTypeSystem];
                btn.frame = CGRectMake(i * theScreenWidth / 4, 0, theScreenWidth / 4, 40);
                [btn addSubview:({
                    UILabel * label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, theScreenWidth / 4, 40)];
                    label.textColor = [UIColor blackColor];
                    label.textAlignment = NSTextAlignmentCenter;
                    label.tag = 301 + i;
                    label.text = _naviDataArray[i][0];
                    label.font = [UIFont systemFontOfSize:12];
                    label;
                })];
                [btn addSubview:({
                    UIImageView * imageView = [[UIImageView alloc] initWithFrame:CGRectMake(theScreenWidth / 4 - 18, 18, 7, 5)];
                    imageView.tag = 401 + i;
                    imageView.image = [UIImage imageNamed:@"down"];
                    imageView;
                })];
                btn.tag = 101 + i;
                [btn addTarget:weakself action:@selector(btnAction:) forControlEvents:UIControlEventTouchUpInside];
                [btn setTintColor:[UIColor grayColor]];
                btn.backgroundColor = [UIColor whiteColor];
                btn;
            })];
        }
        [MBProgressHUD hideAllHUDsForView:weakself.view animated:YES];
    }];
}

#pragma mark collectionview的代理方法
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return _dataArray.count;
    
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    SelectItem * item = _dataArray[indexPath.row];
    static NSString * cellid = @"cell";
    UICollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellid forIndexPath:indexPath];
    [cell.layer setCornerRadius:5];
    [cell.layer setMasksToBounds:YES];
    
    cell.backgroundColor = [UIColor whiteColor];
    UIImageView * imageView = (UIImageView *)[cell.contentView viewWithTag:70];
    if (imageView == nil) {
        imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, (theScreenWidth - 30) / 2, (theScreenWidth - 30) / 2)];
        [cell.contentView addSubview:imageView];
        imageView.tag = 70;
    }
    UILabel * nameLabel = (UILabel *)[cell.contentView viewWithTag:71];
    if (nameLabel == nil) {
        nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(5, (theScreenWidth - 30) / 2 + 5, (theScreenWidth - 30) / 2 - 10, 40)];
        nameLabel.numberOfLines = 2;
        nameLabel.tag = 71;
        nameLabel.font = [UIFont systemFontOfSize:12];
        [cell.contentView addSubview:nameLabel];
    }
    UILabel * priceLabel = (UILabel *)[cell.contentView viewWithTag:72];
    if (priceLabel == nil) {
        priceLabel = [[UILabel alloc] initWithFrame:CGRectMake(5, (theScreenWidth - 30) * 3 / 4 - 30, 75, 20)];
        priceLabel.tag = 72;
        priceLabel.textColor = [UIColor redColor];
        priceLabel.font = [UIFont systemFontOfSize:13];
        [cell.contentView addSubview:priceLabel];
    }
    UILabel * favouriteLabel = (UILabel *)[cell.contentView viewWithTag:73];
    if (favouriteLabel == nil) {
        favouriteLabel = [[UILabel alloc] initWithFrame:CGRectMake((theScreenWidth - 30) / 2 - 40, (theScreenWidth - 30) * 3 / 4 - 30, 40, 20)];
        favouriteLabel.numberOfLines = 2;
        favouriteLabel.tag = 73;
        favouriteLabel.textColor = [UIColor grayColor];
        favouriteLabel.font = [UIFont systemFontOfSize:10];
        [cell.contentView addSubview:favouriteLabel];
    }
    
    [imageView setImageWithURL:[NSURL URLWithString:item.cover_image_url]];
    nameLabel.text = item.name;
    priceLabel.text = item.price;
    favouriteLabel.text = [NSString stringWithFormat:@"%d",[item.favorites_count intValue]];
    return cell;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake((theScreenWidth - 30) / 2, (theScreenWidth - 30) * 3 / 4);
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
    HotDetailViewController * vc = [[HotDetailViewController alloc] init];
    SelectItem * item = _dataArray[indexPath.row];
    vc.webStr = [NSString stringWithFormat:@"http://www.liwushuo.com/items/%@",item.Id];
    [self.navigationController pushViewController:vc animated:YES];
    
}

//返回列与列之间最小的间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
    return 0;
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(10, 10, 0, 10);
}


#pragma mark 按钮出发时间
- (void)btnAction:(UIButton *)btn{
    for (int i = 0; i < 4; i ++) {
        UIScrollView * x = (UIScrollView *)[self.view viewWithTag:201 + i];
        [x removeFromSuperview];
        UIImageView * imageView = (UIImageView *)[self.view viewWithTag:i + 401];
        imageView.image = [UIImage imageNamed:@"down"];
    }
    UIScrollView * scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 40, theScreenWidth, 0)];
    scrollView.contentSize = CGSizeMake(theScreenWidth, ([_naviDataArray[btn.tag - 101] count] - 2) / 3 * 50 + 2);
    
    scrollView.backgroundColor = [UIColor whiteColor];
    scrollView.userInteractionEnabled = YES;
    scrollView.tag = btn.tag + 100;
    [self.view addSubview:scrollView];
    for (int i = 0; i < [_naviDataArray[btn.tag - 101] count] - 1 ; i ++) {
        SelectNavigationItem * item = _naviDataArray[btn.tag - 101][i];
        UIButton * button = [[UIButton alloc] initWithFrame:CGRectMake(10 + theScreenWidth / 3.1 * (i % 3), 10 + 40 * (i / 3), theScreenWidth / 3.4, 30)];
        button.tag = btn.tag * 100 + i;
        button.titleLabel.font = [UIFont systemFontOfSize:13];
        [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        button.layer.borderWidth = 0.5;
        button.layer.borderColor = [[UIColor grayColor]CGColor];
        button.layer.cornerRadius = 5;
        button.layer.masksToBounds = YES;
        if (i == 0) {
            [button setTitle:@"全部" forState:UIControlStateNormal];
        }else
            [button setTitle:item.name forState:UIControlStateNormal];
        [button addTarget:self action:@selector(changeAction:) forControlEvents:UIControlEventTouchUpInside];
        [scrollView addSubview:button];
    }
    [UIView beginAnimations:@"" context:nil];
    [UIView setAnimationDuration:0.5];
    [UIView setAnimationDelegate:self];
    CGRect r = scrollView.frame;
    r.size.height = 150;
    scrollView.frame = r;
    [UIView commitAnimations];
//    把下拉的箭头变成上
    UIImageView * imageView = (UIImageView *)[self.view viewWithTag:btn.tag + 300];
    imageView.image = [UIImage imageNamed:@"up"];
}

- (void)changeAction:(UIButton *)btn{
    __weak SelectViewController * weakself = self;
    if (btn.tag % 100 == 0) {
        [_contentDict setObject:@"" forKey:[_naviDataArray[btn.tag / 100 - 101] lastObject]];
        [_url setString:[NSString stringWithFormat:@"http://api.liwushuo.com/v2/search/item_by_type?price=%@&personality=%@&limit=%@&offset=%@&target=%@&scene=%@",_contentDict[@"price"],_contentDict[@"personality"],_contentDict[@"limit"],_contentDict[@"offset"],_contentDict[@"target"],_contentDict[@"scene"]]];
        NetWorkManager * manager = [[NetWorkManager alloc] init];
        [manager getSelectContentDataWithUrl:_url andBlock:^(id respond) {
            _dataArray = [[NSMutableArray alloc] initWithArray:respond];
            [_collectionView reloadData];
        }];
        for (int i = 0; i < 4; i ++) {
            UIScrollView * x = (UIScrollView *)[weakself.view viewWithTag:201 + i];
            [x removeFromSuperview];
            UIImageView * imageView = (UIImageView *)[weakself.view viewWithTag:i + 401];
            imageView.image = [UIImage imageNamed:@"down"];
        }
        UILabel * label = (UILabel *)[weakself.view viewWithTag:btn.tag / 100 + 200];
        label.text = @"全部";
        
    }else{
        SelectNavigationItem * item = _naviDataArray[btn.tag / 100 - 101][btn.tag % 100];
        [_contentDict setObject:item.key forKey:[_naviDataArray[btn.tag / 100 - 101] lastObject]];
        [_url setString:[NSString stringWithFormat:@"http://api.liwushuo.com/v2/search/item_by_type?price=%@&personality=%@&limit=%@&offset=%@&target=%@&scene=%@",_contentDict[@"price"],_contentDict[@"personality"],_contentDict[@"limit"],_contentDict[@"offset"],_contentDict[@"target"],_contentDict[@"scene"]]];
        NetWorkManager * manager = [[NetWorkManager alloc] init];
        [manager getSelectContentDataWithUrl:_url andBlock:^(id respond) {
            _dataArray = [[NSMutableArray alloc] initWithArray:respond];
            [_collectionView reloadData];
        }];
        
        for (int i = 0; i < 4; i ++) {
            UIScrollView * x = (UIScrollView *)[weakself.view viewWithTag:201 + i];
            [x removeFromSuperview];
        }
//        点击搜索范围后箭头变成下
        UIImageView * imageView = (UIImageView *)[weakself.view viewWithTag:btn.tag / 100 + 300];
        imageView.image = [UIImage imageNamed:@"down"];
        UILabel * label = (UILabel *)[weakself.view viewWithTag:btn.tag / 100 + 200];
        label.text = item.name;
    }
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillAppear:(BOOL)animated{
    [self.navigationController.navigationBar setHidden:NO];
    [self.tabBarController.tabBar setHidden:NO];
    self.navigationController.navigationBar.translucent = NO;
    self.tabBarController.tabBar.translucent = YES;
}
/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
